package com.matchmealpha;

import android.app.Activity;

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

// ----------------------------------------------------------------------

public class CameraActivity extends Activity implements PictureCallback,
		OnClickListener, Camera.AutoFocusCallback{
	private Preview mPreview;
	private Button snapButton;
	private Button cancelButton;
	private CustomSideView side1;
	public static final String IMAGE_FILE_NAME = "IMAGE_FILE_NAME";
	public static final String IMAGE_PIXELS = "IMAGE_PIXELS";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Hide the window title.
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		// Create our Preview view and set it as the content of our activity.
		// mPreview = new Preview(this);
		setContentView(R.layout.share_view);

		mPreview = (Preview) findViewById(R.id.cameraPreview);
		side1 = (CustomSideView) findViewById(R.id.side1);
		snapButton = (Button) findViewById(R.id.ShareSnapButton);
		cancelButton = (Button) findViewById(R.id.ShareCancelButton);

		cancelButton.setOnClickListener(this);
		snapButton.setOnClickListener(this);
		mPreview.setOnClickListener(this);
		

	}

	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		// TODO

		///java.io.File file = new File(Environment.getExternalStorageDirectory()
		//		.getAbsolutePath(), System.currentTimeMillis() + ".png");

		//try {
			////java.io.FileOutputStream os = new FileOutputStream(file);
		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize = 32;
			Bitmap im = BitmapFactory.decodeByteArray (data, 0, data.length);
			//im = getResizedBitmap(im, 400, 400);
			
			// Log.d("X", ((im.getWidth()-im.getHeight() )/2) + "");
			 //   Log.d("Y", "0");
			 //   Log.d("WIDTH", (int)(im.getWidth()-(im.getWidth()*(2*side1.getRatio()))) + "");
			//    Log.d("HEIGHT", im.getHeight() + "");
		 //   im = Bitmap.createBitmap(im, (int)(side1.getRatio()*(im.getWidth())), 0, (int)(im.getWidth()-(im.getWidth()*(2*side1.getRatio()))), im.getHeight());
		   
		  //  im = Bitmap.createBitmap(im,  ((im.getWidth()-im.getHeight() )/2), 0,im.getWidth() -  2*((im.getWidth() - im.getHeight())/2), im.getHeight());
		    im = Bitmap.createScaledBitmap(im, 250, 250, true);
		    //im = getResizedBitmap(im, 600, 600);
		    
		   // int[] pixels = new int[300*300];
		    
		//    im.getPixels(pixels, 0, 300, 0, 0, 300, 300);
		    
		 //   im.recycle();
		    
			//ByteArrayOutputStream baos = new ByteArrayOutputStream();  
			//im.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
			//byte[] b = baos.toByteArray();  
		   // IntArrayOutputStream ios = new IntArrayOutputStream(os); 
		   /// byte[] b = toBytes(pixels);
			//os.write(b);
			//os.flush();
			//os.close();
		    //mPreview.mCamera.release();
			//mPreview.mCamera = null;
		    //ShareActivity.CURRENT_IMAGE = Bitmap.createBitmap(im);
		    ShareActivity.ORIGINAL_IMAGE = im;
		    
			Intent in = new Intent();
		//	in.putExtra(CameraActivity.IMAGE_FILE_NAME, file.getAbsolutePath());
			//in.putExtra(CameraActivity.IMAGE_PIXELS, pixels);
			this.setResult(RESULT_OK, in);
			this.finish();

		////} catch (Exception e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		//	this.setResult(RESULT_CANCELED);
		//	this.finish();
		//}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case (R.id.ShareSnapButton):
			snapButton.setEnabled(false);
			mPreview.mCamera.autoFocus (this);
			break;
		case (R.id.ShareCancelButton):
			
			this.setResult(RESULT_CANCELED);
		this.finish();
			break;
		}
		

	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {

	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {  	
	    	this.setResult(RESULT_CANCELED);
			this.finish();
			Toast.makeText(this, "BACK", Toast.LENGTH_LONG);
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		// CREATE A MATRIX FOR THE MANIPULATION

		Matrix matrix = new Matrix();

		// RESIZE THE BIT MAP

		matrix.postScale(scaleWidth, scaleHeight);

		// RECREATE THE NEW BITMAP

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

		return resizedBitmap;

		}

	@Override
	public void onAutoFocus(boolean arg0, Camera arg1) {
		// TODO Auto-generated method stub
		mPreview.mCamera.takePicture(null, null, this);
	}
	
}
	

// ----------------------------------------------------------------------

class Preview extends SurfaceView implements SurfaceHolder.Callback {
	SurfaceHolder mHolder;
	Camera mCamera;

	Preview(Context context) {
		super(context);

		// Install a SurfaceHolder.Callback so we get notified when the
		// underlying surface is created and destroyed.
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public Preview(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// The Surface has been created, acquire the camera and tell it where
		// to draw.
		mCamera = Camera.open();
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException exception) {
			mCamera.release();
			mCamera = null;
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		mCamera.stopPreview();
		mCamera.release();
		mCamera = null;
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		// Now that the size is known, set up the camera parameters and begin
		// the preview.
		Camera.Parameters parameters = mCamera.getParameters();
		// / parameters.setPreviewSize(w, h);
		// mCamera.setParameters(parameters);
		mCamera.startPreview();

	}

	public Camera getCamera() {
		return mCamera;
	}

}
